package com.ruoyi.web.controller.jjm;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.jjm.domain.*;
import com.ruoyi.jjm.service.*;
import com.ruoyi.jjm.vo.VillageInfo;
import com.ruoyi.system.domain.SysDept;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 村民购煤订单Controller
 * 
 * @author tsr
 * @date 2020-07-15
 */
@Controller
@RequestMapping("/jjm/clientUserorder")
public class ClientUserOrderController extends BaseController
{
    private String prefix = "jjm/clientUserorder";

    @Autowired
    private IClientUserOrderService clientUserOrderService;
    @Autowired
    private IClientUserService clientUserService;
    @Autowired
    private ISupplierOrderService supplierOrderService;

    @Autowired
    private ISupplierService supplierService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private IUserReceiveService receiveService;
    @Autowired
    private ISysUserService userService;

    @GetMapping()
    public String clientUserorder(Long villageId,ModelMap mmap)
    {
        mmap.put("villageId",villageId);
        return prefix + "/clientUserorder";
    }

    /**
     * 查询村民购煤订单列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ClientUserOrder clientUserOrder)
    {
        startPage();
        List<ClientUserOrder> list = clientUserOrderService.searchByFilter(clientUserOrder);
        return getDataTable(list);
    }


    @PostMapping("/listTable")
    @ResponseBody
    public TableDataInfo listTable(ClientUserOrder clientUserOrder)
    {
        List<ClientUserOrderTable> tableList = new ArrayList<>();
        startPage();
        List<ClientUserOrder> list = clientUserOrderService.searchByFilter(clientUserOrder);
        if(CollectionUtils.isNotEmpty(list)){
            for(ClientUserOrder order : list){
                UserReceive receive = receiveService.selectUserReceiveByUserOrderId(order.getId());
                order.setUserReceive(receive);
                tableList.add(new ClientUserOrderTable(order));
            }
        }
        return getDataTable(tableList);
    }
    /**
     * 导出村民购煤订单列表
     */
//    @RequiresPermissions("jjm:clientUserorder:export")
    @Log(title = "村民购煤订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ClientUserOrder clientUserOrder)
    {
        List<ClientUserOrderTable> excelList = new ArrayList<>();
        List<ClientUserOrder> list = clientUserOrderService.searchByFilter(clientUserOrder);
        if(CollectionUtils.isNotEmpty(list)){
            for(ClientUserOrder order : list){
                UserReceive receive = receiveService.selectUserReceiveByUserOrderId(order.getId());
                order.setUserReceive(receive);
                excelList.add(new ClientUserOrderTable(order));
            }
        }
        ExcelUtil<ClientUserOrderTable> util = new ExcelUtil<>(ClientUserOrderTable.class);
        return util.exportExcel(excelList, "洁净煤发放信息","洁净煤发放信息录入");
    }

    @GetMapping("/listClientUser")
    @ResponseBody
    public AjaxResult listClientUser(@RequestParam(name = "villageId",required = false) Long villageId){
        if(villageId == null){
            villageId = ShiroUtils.getSysUser().getDeptId();
        }
        ClientUser filter = new ClientUser();
        filter.setVillageId(villageId);
        List<ClientUser> list = clientUserService.selectClientUserList(filter);
        return AjaxResult.success(list);
    }
    @GetMapping("/listDeliverClientUser")
    @ResponseBody
    public AjaxResult listDeliverClientUser(@RequestParam(name = "villageId",required = false) Long villageId){
        if(villageId == null){
            villageId = ShiroUtils.getSysUser().getDeptId();
        }
        List<ClientUser> list = clientUserService.selectClientUserOrderList(villageId);
        return AjaxResult.success(list);
    }
    /**
     * 已付款待发煤
     * @param mmap
     * @return
     */
    @GetMapping("/waitForGrant")
    public String waitForGrant( ModelMap mmap) {

        SysUser user = ShiroUtils.getSysUser();
        ClientUserOrder sumOrder = clientUserOrderService.sumOrder(user.getDeptId());
        mmap.put("sumOrder",sumOrder);
        mmap.put("user",user);
        return prefix+"/waitForGrant";
    }
    /**
     * 已付款待发煤
     * @param mmap
     * @return
     */
    @GetMapping("/purchase")
    public String purchase( ModelMap mmap) {
        SysUser user = ShiroUtils.getSysUser();
        ClientUserOrder sumOrder = clientUserOrderService.sumOrder(user.getDeptId());
        mmap.put("sumOrder",sumOrder);
        List<Supplier> supplierList = supplierService.selectSupplierList(new Supplier());
        mmap.put("supplierList",supplierList);
        return prefix+"/purchase";
    }


    @GetMapping("/deliver")
    public String deliver( ModelMap mmap) {

        SysUser user = ShiroUtils.getSysUser();

        Double receiveNumber = supplierOrderService.sumConfirmByVillage(user.getDeptId());
        Double deliverNumber = supplierOrderService.sumConfirmByVillage(user.getDeptId());
//        ClientUserOrder sumOrder = clientUserOrderService.sumOrder(user.getDeptId());
        mmap.put("receiveNumber",receiveNumber);
        mmap.put("deliverNumber",deliverNumber);
        mmap.put("user",user);
        return prefix+"/deliver";
    }

    /**
     * 新增村民购煤订单
     */
    @GetMapping("/add")
    public String add(@RequestParam(value = "villageId",required = false)Long villageId,@RequestParam(value = "type",required = false)Integer type,ModelMap modelMap)
    {
        if(villageId != null){
            modelMap.put("villageId",villageId);
        }
        if(type != null){
            modelMap.put("type",type);
        }
        return prefix + "/add";
    }
    @GetMapping("/addDeliver")
    public String addDeliver(@RequestParam(value = "villageId",required = false)Long villageId,ModelMap modelMap)
    {
        if(villageId != null){
            modelMap.put("villageId",villageId);
        }
        return prefix + "/addDeliver";
    }

    /**
     * 新增保存村民购煤订单
     */
//    @RequiresPermissions("jjm:clientUserorder:add")
    @Log(title = "村民购煤订单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    @Transactional
    public AjaxResult addSave(ClientUserOrder clientUserOrder)
    {
        SysUser sysUser = ShiroUtils.getSysUser();
        clientUserOrder.setStatus(1);
        clientUserOrder.setCreateBy(ShiroUtils.getLoginName());
        clientUserOrder.setUpdateBy(ShiroUtils.getLoginName());
        if(clientUserOrder.getVillageId() == null && sysUser.getDeptLevel().intValue() == 4){
            clientUserOrder.setVillageId(sysUser.getDeptId());
        }
        clientUserOrderService.insertClientUserOrder(clientUserOrder);
        saveReceiver(clientUserOrder);
        return toAjax(1);
    }

    /**
     * 修改村民购煤订单
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, @RequestParam("type") Integer type, ModelMap mmap)
    {
        ClientUserOrder clientUserOrder = clientUserOrderService.selectClientUserOrderById(id);
        mmap.put("clientUserOrder", clientUserOrder);
        mmap.put("type", type);
        return prefix + "/edit";
    }

    /**
     * 修改保存村民购煤订单
     */
    @Log(title = "村民购煤订单", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    @Transactional
    public AjaxResult editSave(ClientUserOrder clientUserOrder)
    {
        if(clientUserOrder.getTakeinTime() != null){
            clientUserOrder.setStatus(2);
        }
        clientUserOrder.setUpdateBy(ShiroUtils.getLoginName());
        clientUserOrderService.updateClientUserOrder(clientUserOrder);
        saveReceiver(clientUserOrder);
        return toAjax(1);
    }

    /**
     * 删除村民购煤订单
     */
    @RequiresPermissions("jjm:clientUserorder:remove")
    @Log(title = "村民购煤订单", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(clientUserOrderService.deleteClientUserOrderByIds(ids));
    }

    /**
     * 确认收煤
     * @param order
     * @return
     */
    @Log(title = "村民确认收煤", businessType = BusinessType.DELETE)
    @PostMapping( "/confirm")
    @ResponseBody
    @Transactional
    public AjaxResult confirm(Long id)
    {
        ClientUserOrder order = clientUserOrderService.selectClientUserOrderById(id);
        if(order == null){
            return AjaxResult.error("居民购煤订单不存在");
        }
        ClientUser clientUser = clientUserService.selectClientUserById(order.getClientUserId());
        if(clientUser == null){
            return AjaxResult.error("居民信息不存在");
        }
        order.setStatus(2);
        order.setTakeinTime(new Date());
        order.setUpdateBy(ShiroUtils.getLoginName());
        ClientUserOrder clientUserOrder = clientUserOrderService.selectClientUserOrderById(order.getId());
        UserReceive receive = new UserReceive();
        receive.setReceiveNum(clientUserOrder.getAmount());
        receive.setReceiveTime(order.getTakeinTime());
        receive.setReceiveName(clientUser.getMasterName());
        receive.setSupplierOrderId(clientUserOrder.getSupplierOrderId());
        receive.setUserId(clientUserOrder.getClientUserId());
        receive.setUserOrderId(clientUserOrder.getId());
        receive.setCreateBy(ShiroUtils.getLoginName());
        receiveService.insertUserReceive(receive);
        return toAjax(clientUserOrderService.updateClientUserOrder(order));
    }

    @RequestMapping("/deliverInfo/{villageId}")
    public String deliverInfo(@PathVariable("villageId") Long villageId,ModelMap modelMap){
        SysDept village = deptService.selectDeptById(villageId);
        modelMap.put("village",village);
        return "jjm/xiang/deliverInfo";
    }

    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, Long villageId) throws Exception
    {

        List<String> errorMsg = new ArrayList<>();
        EasyExcel.read(file.getInputStream(),ClientUserOrderTable.class,new AnalysisEventListener<ClientUserOrderTable>(){
            List<ClientUserOrderTable> list = new ArrayList<>();
            @Override
            public void invoke(ClientUserOrderTable clientUserOrderTable, AnalysisContext analysisContext) {
                list.add(clientUserOrderTable);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                String loginName = ShiroUtils.getSysUser().getLoginName();
                if(CollectionUtils.isNotEmpty(list)) {
                    ClientUser filter = new ClientUser();
                    for (int i = 0; i < list.size(); i++) {
                        ClientUserOrderTable orderTable = list.get(i);
                        if (StringUtils.isBlank(orderTable.getMasterName()) || StringUtils.isBlank(orderTable.getMasterIdentityCardNumber()) || StringUtils.isBlank(orderTable.getMasterPhoneNumber())) {

                            errorMsg.add("第" + i + "行，居民信息不完整。");
                            continue;
                        }
                        ClientUser user = null;
                        filter.setMasterName(orderTable.getMasterName());
                        filter.setMasterIdentityCardNumber(orderTable.getMasterIdentityCardNumber());
                        List<ClientUser> userList = clientUserService.selectClientUserList(filter);
                        if (userList != null && userList.size() > 0) {
                            user = userList.get(0);
                        }
                        if (user == null) {
                            errorMsg.add("第" + i + "行，居民信息不存在。");
                            continue;
                        }
                        ClientUserOrder order = new ClientUserOrder();
                        order.setClientUserId(user.getId());
                        order.setVillageId(villageId);
                        order.setUpdateBy(loginName);
                        order.setCreateBy(loginName);
                        if (orderTable.getCreateTime() != null) {
                            order.setCreateTime(DateUtils.dateTime("yyyy.MM.dd", orderTable.getCreateTime()));
                        }
                        order.setStatus(1);
                        if (orderTable.getTakeinTime() != null) {
                            order.setTakeinTime(DateUtils.dateTime("yyyy.MM.dd", orderTable.getTakeinTime()));
                            order.setStatus(2);

                        }
                        if(orderTable.getAmount() != null){
                            order.setAmount(new BigDecimal(orderTable.getAmount()));
                        }
                        if(orderTable.getMoney() != null){
                            order.setMoney(new BigDecimal(orderTable.getMoney()));
                        }
                        clientUserOrderService.insertClientUserOrder(order);
                        saveReceiver(order,orderTable);

                    }
                }
            }
        }).sheet().headRowNumber(1).doRead();
//        ExcelUtil<ClientUserOrderTable> util = new ExcelUtil<>(ClientUserOrderTable.class);
//        List<ClientUserOrderTable> list = util.importExcel(file.getInputStream());

        if(errorMsg.size() > 0){
            return AjaxResult.error(String.join("<br>",errorMsg));
        }
        return AjaxResult.success("上传成功。");
    }

    private void saveReceiver(ClientUserOrder order,ClientUserOrderTable orderTable){
        if(order.getStatus() == 2){
            UserReceive receive = new UserReceive();
            receive.setCreateBy(ShiroUtils.getLoginName());
            receive.setUserOrderId(order.getId());
            receive.setSupplierOrderId(order.getSupplierOrderId());
            receive.setUserId(order.getClientUserId());
            receive.setReceiveTime(order.getTakeinTime());
            if(orderTable.getReceiveAmount() != null){
                receive.setReceiveNum(new BigDecimal(orderTable.getReceiveAmount()));
            }
            receive.setReceiveName(orderTable.getReceiver());
            receiveService.insertUserReceive(receive);
        }
    }
    private void saveReceiver(ClientUserOrder order){
        if(order.getStatus() != null && order.getStatus() == 2){
            UserReceive receive = receiveService.selectUserReceiveByUserOrderId(order.getId());
            if(receive == null){
                receive = new UserReceive();
            }
            receive.setCreateBy(ShiroUtils.getLoginName());
            receive.setUserOrderId(order.getId());
            receive.setSupplierOrderId(order.getSupplierOrderId());
            receive.setUserId(order.getClientUserId());
            receive.setReceiveTime(order.getTakeinTime());
            receive.setReceiveNum(order.getAmount());
            ClientUser user = clientUserService.selectClientUserById(order.getClientUserId());
            receive.setReceiveName(user.getMasterName());
            if(receive.getId() == null){
                receiveService.insertUserReceive(receive);
            }else{
                receiveService.updateUserReceive(receive);
            }
        }
    }
}
